package vip.xiaonuo.hontu.issued.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import vip.xiaonuo.hontu.issued.constant.HTConstant;
import vip.xiaonuo.hontu.issued.response.HTBaseResponse;
import vip.xiaonuo.hontu.issued.response.UploadImageResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import okhttp3.*;
import java.util.concurrent.TimeUnit;
import vip.xiaonuo.core.exception.ServiceException;

public class HT_DEVICE_POST {

    public static final String APP_KEY = "appkey1";

    public static final String APP_SECRET = "sdfajk3242324fa!djq7";

    public static void main(String[] args) throws Exception {

//        //请求参数，form表单方式，鸿图大部分接口都是body传参，故这里大部分都是""，如果有参数，查看文档说明
//        // 要请求的url,看要请求的接口说明
//        String url = "/v1/api/device/list";
//        String ip = "192.168.1.150";
//        String port = "80";
//
//        // 构建请求体，看要请求的接口说明
//        Object deviceReq = DeviceReq.builder().name("core").build();
//        Object o = postJson(url, ip, port, deviceReq, Object.class);
//        System.out.println(o);

        // 时间戳，用户自己生成
        String ctimestamp = System.currentTimeMillis() + "";
        System.out.println(ctimestamp);
        // 6位随机码，用户自己生成
        String cnonce = getStringRandom();
        System.out.println(cnonce);

        String sign = SignUtlis.sign("1684825048249", "802575", null, "",
                "/v1/api/person/config/uploadImage", "POST", "appkey1", "sdfajk3242324fa!djq7");
        System.out.println(sign);
    }


    public static void qualityJudge(String fileUrl, String ip, String port) {
        // appkey,固定，
        String cappKey = "appkey1";
        // 秘钥，固定
        String secret = "sdfajk3242324fa!djq7";

        // 时间戳，用户自己生成
        String ctimestamp = System.currentTimeMillis() + "";

        // 6位随机码，用户自己生成
        String cnonce = getStringRandom();

        String requestParam = "";

        // 请求方式,看要请求的接口说明
        String method = "POST";

        // 计算签名
        String csign = SignUtlis.sign(ctimestamp, cnonce, "", requestParam, "/v1/api/misc/file/qualityJudge", method, cappKey, secret);

        //签名信息
        Map<String, String> files = new HashMap<>();
        files.put("cappkey", "appkey1");
        files.put("cnonce", "1234344");
        files.put("ctimestamp", ctimestamp);
        //files.put("csign", "974228f6c7c56bb1320f8501c01aa991");
        files.put("csign", csign);
        String rets = OkHttpUtil.getInstance(false).doPostFormMultipart("http://"+ip + ":" + port + "/v1/api/misc/file/qualityJudge", fileUrl, files);
        HTBaseResponse uploadImageResponse = JSON.parseObject(rets, HTBaseResponse.class);
        if (!ObjectUtil.equal(uploadImageResponse.getCode(), "0")) {
            throw new ServiceException(500, "图片检测异常，异常信息【" + rets + "】" + Optional.ofNullable(HTConstant.QUALITY_JUDGE_MAP.get(uploadImageResponse.getCode())).orElse("未知异常"));
        }

    }


    public static String uploadImage(String fileUrl, String ip, String port) {
        // appkey,固定，
        String cappKey = "appkey1";
        // 秘钥，固定
        String secret = "sdfajk3242324fa!djq7";

        // 时间戳，用户自己生成
        String ctimestamp = System.currentTimeMillis() + "";

        // 6位随机码，用户自己生成
        String cnonce = getStringRandom();

        String requestParam = "";

        // 请求方式,看要请求的接口说明
        String method = "POST";

        // 计算签名
        String csign = SignUtlis.sign(ctimestamp, cnonce, null, requestParam, "/v1/api/person/config/uploadImage", method, cappKey, secret);

        //签名信息
        Map<String, String> files = new HashMap<>();
        files.put("cappkey", "appkey1");
        files.put("cnonce", cnonce);
        files.put("ctimestamp", ctimestamp);
        files.put("csign", csign);
        //http 地址请求 ；false 表示
        //String ret = OkHttpUtil.getInstance(false).doPostFormMultipart(ip + ":" + port + "/api/person/uploadImage", fileUrl, files);
        String rets = OkHttpUtil.getInstance(false).doPostFormMultipart("http://"+ip + ":" + port + "/v1/api/person/config/uploadImage", fileUrl, files);
        UploadImageResponse uploadImageResponse = JSON.parseObject(rets, UploadImageResponse.class);
        if (ObjectUtil.equal(uploadImageResponse.getCode(), 0)) {
            return uploadImageResponse.getData().getUri();
        } else {
            throw new ServiceException(500, "上传图片发生异常，异常信息【" + rets + "】");
        }

    }



    /**
     * 发送json 请求
     *
     * @param url
     * @param ip
     * @param port
     * @param deviceReq
     * @return
     * @throws IOException
     */
    public static <T> T postJson(String url, String ip, String port, Object deviceReq, Class<T> returnType) throws Exception {

        // appkey,固定，
        String cappKey = "appkey1";
        // 秘钥，固定
        String secret = "sdfajk3242324fa!djq7";

        // 时间戳，用户自己生成
        String ctimestamp = System.currentTimeMillis() + "";

        // 6位随机码，用户自己生成
        String cnonce = getStringRandom();

        String requestParam = "";

        // 请求方式,看要请求的接口说明
        String method = "POST";

        // 计算签名
        String csign = SignUtlis.sign(ctimestamp, cnonce, deviceReq, requestParam, url, method, cappKey, secret);

        // 发起请求
        String realUrl = "http://" + ip + ":" + port + url;

        return JSON.parseObject(postJson(ctimestamp, cnonce, cappKey, csign, deviceReq, realUrl), returnType);

    }

    /**
     * 发送json 请求
     *
     * @param url
     * @param ip
     * @param port
     * @return
     * @throws IOException
     */
    public static <T> T getJson(String url, String ip, String port,  Class<T> returnType) throws Exception {

        // 时间戳，用户自己生成
        String ctimestamp = System.currentTimeMillis() + "";

        // 6位随机码，用户自己生成
        String cnonce = getStringRandom();

        // 计算签名
        String csign = SignUtlis.sign(ctimestamp, cnonce, null, "", url, "GET", APP_KEY, APP_SECRET);

        // 发起请求
        String realUrl = "http://" + ip + ":" + port + url;

        return JSON.parseObject(getJson(ctimestamp, cnonce, APP_KEY, csign, realUrl), returnType);

    }


    public static String getStringRandom() {
        Random random = new Random();
        //把随机生成的数字转成字符串
        String str = String.valueOf(random.nextInt(9));
        for (int i = 0; i < 5; i++) {
            str += random.nextInt(9);
        }
        if (str.length()>6){
            str=str.substring(0,6);
        }
        return str;
    }

    private static String postJson(String ctimestamp, String cnonce, String cappKey, String csign, Object reqeustData, String url) throws Exception {
        String bodyJson = JSONObject.toJSONString(reqeustData);
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.SECONDS)
                .readTimeout(30000, TimeUnit.SECONDS)
                .writeTimeout(30000, TimeUnit.SECONDS)
                .addNetworkInterceptor(new HTOkHttpInterceptor()).build();
        MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
        RequestBody requestBody = RequestBody.create(mediaType, bodyJson);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("cnonce", cnonce)
                .addHeader("ctimestamp", ctimestamp)
                .addHeader("cappKey", cappKey)
                .addHeader("csign", csign)
                .post(requestBody)
                .build();
        Call call = httpClient.newCall(request);
        Response response = call.execute();
        if (response.body() != null) {
            return response.body().string();
        } else {
            throw new ServiceException(500, "没有任何返回信息!");
        }

    }


    private static String getJson(String ctimestamp, String cnonce, String cappKey, String csign, String url) throws Exception {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .connectTimeout(3000, TimeUnit.SECONDS)
                .readTimeout(30000, TimeUnit.SECONDS)
                .writeTimeout(30000, TimeUnit.SECONDS)
                .addNetworkInterceptor(new HTOkHttpInterceptor()).build();
        Request request = new Request.Builder()
                .url(url)
                .addHeader("cnonce", cnonce)
                .addHeader("ctimestamp", ctimestamp)
                .addHeader("cappKey", cappKey)
                .addHeader("csign", csign)
                .get()
                .build();
        Call call = httpClient.newCall(request);
        Response response = call.execute();
        if (response.body() != null) {
            return response.body().string();
        } else {
            throw new ServiceException(500, "没有任何返回信息!");
        }

    }
}